package com.atguigu.day09;

import com.atguigu.bean.WaterSensor;
import com.sun.xml.internal.bind.v2.TODO;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.annotation.DataTypeHint;
import org.apache.flink.table.annotation.FunctionHint;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.table.functions.ScalarFunction;
import org.apache.flink.table.functions.TableFunction;
import org.apache.flink.types.Row;

import static org.apache.flink.table.api.Expressions.$;
import static org.apache.flink.table.api.Expressions.call;

public class Flink02_UDF_TableFun {
    public static void main(String[] args) {
        //1获取流的执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        env.setParallelism(1);

        //2.从端口读取数据
        SingleOutputStreamOperator<WaterSensor> streamOperator = env.socketTextStream("localhost", 9999)
                .map(new MapFunction<String, WaterSensor>() {
                    @Override
                    public WaterSensor map(String value) throws Exception {
                        String[] split = value.split(",");
                        return new WaterSensor(split[0], Long.parseLong(split[1]), Integer.parseInt(split[2]));
                    }
                });


        //3.获取表的执行环境
        StreamTableEnvironment tableEnv = StreamTableEnvironment.create(env);

        //4.将流转为表
        Table table = tableEnv.fromDataStream(streamOperator);

      /*  table
                .joinLateral(call(MyUDTF.class,$("id")))
                .select($("id"),$("str1"))
                .execute()
                .print();*/

//        TODO 注册一个自定义函数
        tableEnv.createTemporarySystemFunction("idExp", MyUDTF.class);

        table
                .joinLateral(call("idExp",$("id")))
                .select($("id"),$("str1"))
                .execute()
                .print();

//        tableEnv.executeSql("select id,str1 from "+table+",lateral table(idExp(id))").print();
        tableEnv.executeSql("select id,str1 from "+table+" left join lateral table(idExp(id)) on true").print();
    }

    //自定义一个表函数（一进多出） 根据id按照下划线切分切出每条数据
    @FunctionHint(output=@DataTypeHint("ROW<str1 string>"))
   public static class MyUDTF extends TableFunction<Row>{
       public void eval(String value){
           String[] strings = value.split("_");
           for (String string : strings) {
               collect(Row.of(string));
           }
       }
    }
}
